﻿using CNKI.TPI.Web.Admin.IDAO;
using CNKI.TPI.Web.Search.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Castle.DynamicProxy;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Admin.IBLL;
using System.Linq.Expressions;
using System.Collections;
using KNet.Data.Entity;
using CNKI.TPI.Web.Search.IDAO;
using CNKI.TPI.Web.Admin.Model;
namespace CNKI.TPI.Web.Admin.BLL
{
    public class SingleDBPublishService : BaseService, ISingleDBPublishService
    {
        private ISingleDBPublishDAO singDbDao = null;
        ICategoryDAO categoryDAO = null;
        IHomeConfigDAO homeConfigDao = null;
        public SingleDBPublishService(ISingleDBPublishDAO singDbDao, ICategoryDAO categoryDAO, IHomeConfigDAO homeConfigDao)
        {
            this.homeConfigDao = this.generator.CreateInterfaceProxyWithTarget<IHomeConfigDAO>(homeConfigDao, new IInterceptor[] { new LogInterceptor() });
            this.singDbDao = this.generator.CreateInterfaceProxyWithTarget<ISingleDBPublishDAO>(singDbDao, new IInterceptor[] { new LogInterceptor() });
            this.categoryDAO = this.generator.CreateInterfaceProxyWithTarget<ICategoryDAO>(categoryDAO, new IInterceptor[] { new LogInterceptor() });
        }

        /// <summary>
        /// 获得数据库列表
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_DATABASE> GetDBList(IList<SearchType> SearchTypeList = null)
        {
            return singDbDao.GetDBList(SearchTypeList);

        }
        /// <summary>
        /// 根据数据库ID获取SYS_CMS_DATABASE实例
        /// </summary>
        /// <param name="databaseId"></param>
        /// <returns></returns>
        public SYS_CMS_DATABASE GetDatabaseByID(int databaseId)
        {
            SYS_CMS_DATABASE result = null;
            try
            {
                result = categoryDAO.GetDatabaseByID(databaseId);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }

            return result;
        }
        /// <summary>
        /// 获得数据库列表,分页
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_DATABASE> GetDBListPageSize(int pageIndexNow, int pageSize, string type, string DbName, out int count, IList<SearchType> SearchTypeList = null)
        {
            ExpressionCombine<SYS_CMS_DATABASE> exp = new ExpressionCombine<SYS_CMS_DATABASE>();
            Expression<Func<SYS_CMS_DATABASE, bool>> match; //查询条件
            if (type != "all")
            {
                exp.And("DatabasePubFlag", OperatorType.Equal, type);
            }

            if (!String.IsNullOrEmpty(DbName))
            {
                exp.And("DatabaseName", OperatorType.Like, DbName);
            }
            if (SearchTypeList != null)
            {
                if (SearchTypeList.Count == 0)
                {
                    count = 0;
                    return new List<SYS_CMS_DATABASE>();
                }
                ExpressionCombine<SYS_CMS_DATABASE> subExp2 = new ExpressionCombine<SYS_CMS_DATABASE>();
                foreach (SearchType item in SearchTypeList)
                {
                    subExp2.Or("SearchType", OperatorType.Equal, (int)item);
                }
                exp.And(subExp2);
            }
            match = exp.Compile();
            Expression<Func<SYS_CMS_DATABASE, bool>> order = null;
            order = c => c.CreateDate.Desc();

            IList<SYS_CMS_DATABASE> list = singDbDao.GetDBListPageSize(match, (pageIndexNow - 1) * pageSize, pageSize, out count, order, false, "SYS_CMS_DATABASE", "");
            ProcessResult(list);
            return list;

        }
        /// <summary>
        /// 获得数据库字段
        /// </summary>
        /// <param name="dbID"></param>
        /// <returns></returns>
        public IList<SYS_CMS_DATABASE_FIELD> GetDBField(string dbCode)
        {
            return singDbDao.GetDBField(dbCode);
        }
        /// <summary>
        /// 获得数据库发布模板信息
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_PUBLISHTYPE> GetTemplateList()
        {
            return singDbDao.GetTemplateList();
        }
        /// <summary>
        /// 一次性发布数据库
        /// </summary>
        /// <param name="dbInfo"></param>
        /// <param name="fieldList"></param>
        /// <returns>0代表成功，-1异常，1代表检索发布失败，2排序失败，3概览失败， 4细缆失败</returns>
        //public int PublishDB(SYS_CMS_DATABASE dbInfo, IList<SYS_CMS_DATABASE_PUBLISH_FIELD> fieldList)
        //{

        //    int result = 0;
        //    try
        //    {
        //        bool flage = false;
        //        Expression<Func<SYS_CMS_DATABASE_PUBLISH_FIELD, bool>> query = c => (c.DbID == dbInfo.SysID.ToString());
        //        flage = singDbDao.DeletePublicField(query);
        //        if (!flage)
        //        {
        //            result = -1;
        //            LogOpr.Error("发布数据库(PublishDB):删除失败(表SYS_CMS_DATABASE_PUBLISH_FIELD)");
        //        }
        //        else //主表更新成功更新子表
        //        {
        //            foreach (SYS_CMS_DATABASE_PUBLISH_FIELD item in fieldList)
        //            {
        //                flage = singDbDao.InsertPublicField(item);
        //                if (!flage)
        //                {
        //                    LogOpr.Error("发布数据库(PublishDB):更新表SYS_CMS_DATABASE_PUBLISH_FIELD失败：FieldType:" + item.FieldType);
        //                    result = int.Parse(item.FieldType);//只要有一个不成功就返回不成功
        //                    break;
        //                }
        //            }
        //        }
        //        if (result == 0)
        //        {
        //            if (!singDbDao.UpdatetDB(dbInfo))
        //            {
        //                result = -1;
        //                LogOpr.Error("发布数据库(PublishDB):更新表SYS_CMS_DATABASE失败!");
        //            }

        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        LogOpr.Error(ex.ToString());
        //    }
        //    return result;
        //}
        /// <summary>
        /// 处理结果集
        /// </summary>
        /// <param name="ds"></param>
        private void ProcessResult(IList<SYS_CMS_DATABASE> list)
        {
            if (list != null)
            {
                foreach (SYS_CMS_DATABASE item in list)
                {
                    item.DatabaseName = StringHelper.ConvertHighlightFlag(item.DatabaseName);
                    SYS_CMS_RESOURCE_TEMPLATE templateobj = homeConfigDao.GetTemplateByID(item.DatabaseType);//获取数据库类型
                    if (templateobj != null)
                    {
                        item.DatabaseTypeName = templateobj.RESOURCENAME;
                    }
                }
            }
        }
        /// <summary>
        /// 更新数据库表
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool UpdatetDBPubFlag(string DbID, int flag)
        {
            bool result = false;
            try
            {
                result = singDbDao.UpdatetDBPubFlag(DbID, flag);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }
        /// <summary>
        /// 更改SYS_CMS_DATABASE_PUBLISH_FIELD表数据
        /// </summary>
        /// <param name="DbID"></param>
        /// <param name="fieldList"></param>
        /// <param name="flage"></param>
        /// <returns></returns>
        public bool PublicField(string DbID, IList<SYS_CMS_DATABASE_PUBLISH_FIELD> fieldList, string flage)
        {
            //不管是更新还是新增都执行先删除后插入的规则
            bool result = false;
            try
            {
               
                //if (flage == "update")//如果是修改，则先删除原有数据
                //{
                Expression<Func<SYS_CMS_DATABASE_PUBLISH_FIELD, bool>> query = c => (c.DbID == DbID && c.FieldType == fieldList[0].FieldType);
                singDbDao.DeletePublicField(query);
                //}
                foreach (SYS_CMS_DATABASE_PUBLISH_FIELD item in fieldList)
                {
                    result = singDbDao.InsertPublicField(item);
                    if (!result)
                    {
                        LogOpr.Error("表SYS_CMS_DATABASE_PUBLISH_FIELD插入数据失败：FieldType:" + item.FieldType);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 获取已经设置的字段
        /// </summary>
        /// <param name="dbID"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public IList<SYS_CMS_DATABASE_PUBLISH_FIELD> GetField(string dbID, FieldType type)
        {
            IList<SYS_CMS_DATABASE_PUBLISH_FIELD> result = null;
            try
            {
                result = singDbDao.GetField(dbID, type);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }

            return result;
        }

        /// <summary>
        /// 更新数据库表 保存发布形式
        /// </summary>
        /// <param name="DbID">数据库ID</param>
        /// <param name="templateID">模板ID</param>
        /// <param name="visibleFlage">是否显示</param>
        /// <returns></returns>
        public bool UpdatetDBTemplate(string DbID, string templateID, string visibleFlage,string dbsort)
        {
            bool result = false;
            try
            {
                result = singDbDao.UpdatetDBTemplate(DbID, templateID, visibleFlage, dbsort);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }
        /// <summary>
        /// 保存显示名称
        /// </summary>
        /// <param name="DbID"></param>
        /// <param name="Name"></param>
        /// <param name="DisplayName"></param>
        /// <returns></returns>
        public bool UpdatetDBDisplayName(string DbID, string Name, string DisplayName)
        {
            bool result = false;
            try
            {
                result = singDbDao.UpdatetDBDisplayName(DbID, Name, DisplayName);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

           /// <summary>
        /// 更改数据库显示顺序
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool UpdateDBSort(IList<SYS_CMS_DATABASE> list)
        {
            return singDbDao.UpdateDBSort(list);
        }

        /// <summary>
        /// 根据查询条件获取数据库列表 分页
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_DATABASE> GetDBListPageSize(int pageIndexNow, int pageSize, out int count,string dbname)
        {
            ExpressionCombine<SYS_CMS_DATABASE> exp = new ExpressionCombine<SYS_CMS_DATABASE>();
            Expression<Func<SYS_CMS_DATABASE, bool>> match; //查询条件
            if (!String.IsNullOrEmpty(dbname))
            {
                exp.And("DatabaseName", OperatorType.Like, dbname);
            }
            exp.And("SearchType", OperatorType.GreaterThan, 1);
            match = exp.Compile();
            Expression<Func<SYS_CMS_DATABASE, bool>> order = null;
            order = c => c.CreateDate.Desc();
            return singDbDao.GetDBListPageSize(match, (pageIndexNow - 1) * pageSize, pageSize, out count, order, false, "SYS_CMS_DATABASE", "");
        }

        /// <summary>
        /// 获得已经设置关联的数据库
        /// </summary>
        /// <param name="dbCode">dbcode为空时，获取所有数据</param>
        /// <returns></returns>
        public IList<SYS_CMS_DATABASE_RELATION> GetDbRelation(string dbCode)
        {
            IList<SYS_CMS_DATABASE_RELATION> list = singDbDao.GetDbRelation(dbCode).Where(c=>c.Status==1).ToList();
            if (list != null)
            {
                foreach (SYS_CMS_DATABASE_RELATION item in list)
                {
                    item.RelationDBName = categoryDAO.GetDatabaseByCode(item.RelationDBCode).DatabaseName;
                    item.RelationDBFieldList = new List<SYS_CMS_DATABASE_FIELD>();
                    IList<SYS_CMS_DATABASE_FIELD> FieldList = GetDBField(item.RelationDBCode);
                    if (FieldList != null)
                    {
                        foreach (SYS_CMS_DATABASE_FIELD fitem in FieldList)
                        {
                            if (!fitem.Field.StartsWith("SYS_") || fitem.Field.Equals("SYS_FLD_VSM"))
                            {
                                item.RelationDBFieldList.Add(fitem);
                            }
                          
                        }
                    }
                   
                }

            }
            return list;
        }

          /// <summary>
        /// 保存关联数据库
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool SaveRelationField(IList<SYS_CMS_DATABASE_RELATION> list)
        {
            bool m = false;
            try
            {
                if (list != null && list.Count > 0)
                {
                    m=singDbDao.DeleteRelation(list[0].DBCode);  //先删除已有管理，在插入
                    if (m)
                    {
                        foreach (SYS_CMS_DATABASE_RELATION item in list)
                        {
                            m = singDbDao.InsertRelation(item);
                        }
                    }

                }
            }
            catch(Exception ex)
            {
                LogOpr.Error(ex.ToString());
                m=false;
            }
            return m;
        
        }
        /// <summary>
        /// 删除数据库关联数据
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
       public bool DeleteRelation(string dbcode)
        {
            return singDbDao.DeleteRelation(dbcode);
       }
        
    }
}
